import { NextRequest, NextResponse } from 'next/server';
import { validateToken } from '@/utils/auth';

// 需要认证的 API 路径
const protectedApiPaths = [
  '/api/users',
  '/api/tickets',
  '/api/auth/me',
];

// 公开的 API 路径
const publicApiPaths = [
  '/api/auth/login',
];

export function middleware(request: NextRequest) {
  const { pathname } = request.nextUrl;

  // 只处理 API 路由
  if (!pathname.startsWith('/api/')) {
    return NextResponse.next();
  }

  // 检查是否为公开 API
  if (publicApiPaths.some(path => pathname.startsWith(path))) {
    return NextResponse.next();
  }

  // 检查是否为需要保护的 API
  const needsAuth = protectedApiPaths.some(path => pathname.startsWith(path));
  
  if (!needsAuth) {
    return NextResponse.next();
  }

  // 获取 Authorization header
  const authHeader = request.headers.get('authorization');
  
  if (!authHeader || !authHeader.startsWith('Bearer ')) {
    return NextResponse.json(
      { success: false, message: '未提供有效的认证信息' },
      { status: 401 }
    );
  }

  const token = authHeader.slice(7); // 移除 'Bearer ' 前缀

  // 验证 token
  if (!validateToken(token)) {
    return NextResponse.json(
      { success: false, message: 'Token 无效或已过期' },
      { status: 401 }
    );
  }

  // Token 有效，继续处理请求
  return NextResponse.next();
}

export const config = {
  matcher: '/api/:path*',
}; 